package com.wchen.project.global.resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Desc:   线程池配置
 * @author: cww
 * @DateTime: 2019-12-27 22:02
 */
@Configuration
public class ExecutorConfig {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean("globalThreadPool")
    public Executor globalThreadPool() {
        logger.info("开始配置线程池");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 定时任务为IO型，当前PC为4核8线程，每轮任务通常2-4个线程，故分配4个也够了
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(6);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Global-Thread-Pool-");
        //当pool到达 MaxPoolSize时执行的策略：让调用者所在线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        logger.info("线程池配置完成");
        return executor;
    }
}
